import jwt from "jsonwebtoken";
import { Request, Response, NextFunction } from 'express'

const tokenMiddleware = (req: Request, res: Response, next: NextFunction): void => {
    const token = req.header("Authorization")?.replace("Bearer ", "");
    if (!token) {
        res.status(401).json({ message: "Unauthorized - No token provided" });
        return;
    }
    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        req.auth = decoded as JwtPayload;
        next();
    } catch (error) {
        res.status(401).json({ message: "Unauthorized - Invalid token" });
    }
    return;
};

export default tokenMiddleware;
